package com.mdd.admin.service.salesman.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mdd.admin.LikeAdminThreadLocal;
import com.mdd.admin.service.googs.ISalesmanGoogsService;
import com.mdd.admin.service.salesman.ISalesmanService;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.validate.salesman.SalesmanParam;
import com.mdd.admin.vo.goods.GoodsDetailVo;
import com.mdd.admin.vo.salesman.SalesmanDetailVo;
import com.mdd.admin.vo.salesman.SalesmanListVo;
import com.mdd.common.constant.GlobalConstant;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.goods.Goods;
import com.mdd.common.entity.salesman.SalesmanGoogs;
import com.mdd.common.entity.salesman.Salesman;
import com.mdd.common.entity.salesman.UserSalesman;
import com.mdd.common.mapper.goods.GoodsMapper;
import com.mdd.common.mapper.salesman.SalesmanMapper;
import com.mdd.common.mapper.salesman.UserSalesmanMapper;
import com.mdd.common.utils.TimeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 推销员实现类
 */
@Service
public class SalesmanServiceImpl extends ServiceImpl<SalesmanMapper, Salesman> implements ISalesmanService {

    @Resource
    private UserSalesmanMapper userSalesmanMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private ISalesmanGoogsService salesmanGoogsService;

    /**
     * 推销员列表
     *
     * @author 蒋海省
     * @param pageParam 分页参数
     * @param params 搜索参数
     * @return PageResult<SalesmanListVo>
     */
    @Override
    public PageResult<SalesmanListVo> list(PageParam pageParam, Map<String, String> params) {
        Integer page  = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();

        QueryWrapper<Salesman> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("id");

        this.baseMapper.setSearch(queryWrapper, params, new String[]{
            "=:userId@user_id:long",
            "like:name:str",
            "like:mobile:str",
            "=:zone:str",
            "=:discount:long",
        });

        IPage<Salesman> iPage = this.baseMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<SalesmanListVo> list = new LinkedList<>();
        for(Salesman item : iPage.getRecords()) {
            SalesmanListVo vo = new SalesmanListVo();
            BeanUtils.copyProperties(item, vo);
//            vo.setId(item.getId());
            if(item.getUpdateTime() != null) {
                vo.setUpdateTime(TimeUtil.timestampToDate(Long.valueOf(item.getUpdateTime())));
            }
            vo.setCreateTime(TimeUtil.timestampToDate(Long.valueOf(item.getCreateTime())));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 推销员详情
     *
     * @author 蒋海省
     * @param id 主键参数
     * @return Salesman
     */
    @Override
    public SalesmanDetailVo detail(Integer id) {
        Salesman model = this.baseMapper.selectOne(
                new QueryWrapper<Salesman>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        SalesmanDetailVo vo = new SalesmanDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 推销员新增
     *
     * @author 蒋海省
     * @param salesmanParam 参数
     */
    @Override
    public void add(SalesmanParam salesmanParam) {
        Salesman model = new Salesman();
        model.setUserId(salesmanParam.getUserId());
        model.setName(salesmanParam.getName());
        model.setMobile(salesmanParam.getMobile());
        model.setZone(salesmanParam.getZone());
        model.setDiscount(salesmanParam.getDiscount());
        model.setStatus(salesmanParam.getStatus());
        model.setCreateTime(Math.toIntExact(System.currentTimeMillis() / 1000));
	    this.baseMapper.insert(model);
    }

    /**
     * 推销员编辑
     *
     * @author 蒋海省
     * @param salesmanParam 参数
     */
    @Override
    public void edit(SalesmanParam salesmanParam) {
        Salesman model = this.baseMapper.selectOne(
                new QueryWrapper<Salesman>()
                    .eq("id",  salesmanParam.getId())
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(salesmanParam.getId());
        model.setUserId(salesmanParam.getUserId());
        model.setName(salesmanParam.getName());
        model.setMobile(salesmanParam.getMobile());
        model.setZone(salesmanParam.getZone());
        model.setDiscount(salesmanParam.getDiscount());
        model.setStatus(salesmanParam.getStatus());
        model.setUpdateTime(Math.toIntExact(System.currentTimeMillis() / 1000));
	    this.baseMapper.updateById(model);
    }

    /**
     * 推销员删除
     *
     * @author 蒋海省
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        Salesman model = this.baseMapper.selectOne(
                new QueryWrapper<Salesman>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime((int) (System.currentTimeMillis() / 1000));
	    this.baseMapper.updateById(model);
    }

    @Override
    public GoodsDetailVo getGoodsDetailForSalesman(Integer id) {
        Integer userId = LikeAdminThreadLocal.getAdminId();
        UserSalesman userSalesman = userSalesmanMapper.selectOne(new LambdaQueryWrapper<UserSalesman>()
                .eq(UserSalesman::getUserId, userId)
                .eq(UserSalesman::getIsDelete, GlobalConstant.NOT_DELETE));
        Goods goods = goodsMapper.selectOne(new LambdaQueryWrapper<Goods>());
        GoodsDetailVo target = new GoodsDetailVo();
        BeanUtils.copyProperties(goods, target);
        if (Objects.isNull(userSalesman)) {
            return target;
        }

        LambdaQueryWrapper<SalesmanGoogs> salesmanGoogsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        salesmanGoogsLambdaQueryWrapper.eq(SalesmanGoogs::getProductId, id);
        Integer salesmanId = userSalesman.getSalesmanId();
        Map<Long, BigDecimal> collect = salesmanGoogsService.list(salesmanGoogsLambdaQueryWrapper).stream().collect(Collectors.toMap(SalesmanGoogs::getSalesmanId, SalesmanGoogs::getProductPrice));
        if (collect.containsKey(salesmanId)) {
            target.setPrice(collect.get(salesmanId));
        }
        return target;
    }

    public Goods getGoodsForSalesman(Integer id) {
        Integer userId = LikeAdminThreadLocal.getAdminId();
        UserSalesman userSalesman = userSalesmanMapper.selectOne(new LambdaQueryWrapper<UserSalesman>()
                .eq(UserSalesman::getUserId, userId)
                .eq(UserSalesman::getIsDelete, GlobalConstant.NOT_DELETE));
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<Goods>().eq(Goods::getId, id).eq(Goods::getIsDelete, GlobalConstant.NOT_DELETE);
        Goods goods = goodsMapper.selectOne(queryWrapper);
        if (Objects.isNull(goods)) {
            return null;
        }
        LambdaQueryWrapper<SalesmanGoogs> salesmanGoogsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        salesmanGoogsLambdaQueryWrapper.eq(SalesmanGoogs::getProductId, id);
        Integer salesmanId = userSalesman.getSalesmanId();
        Map<Long, BigDecimal> collect = salesmanGoogsService.list(salesmanGoogsLambdaQueryWrapper).stream().collect(Collectors.toMap(SalesmanGoogs::getSalesmanId, SalesmanGoogs::getProductPrice));
        if (collect.containsKey(salesmanId)) {
            goods.setPrice(collect.get(salesmanId));
        }
        return goods;
    }

}
